package org.demo.nio.reactor.simple;

import java.io.IOException;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * Created by tangwy on 2017/10/30.
 */
public class Acceptor implements Runnable {
    private Selector selector;
    private ServerSocketChannel channel;

    public Acceptor(Selector selector, ServerSocketChannel channel) {
        if(selector==null){
            throw new NullPointerException("selector is null");
        }
        if(channel==null){
            throw new NullPointerException("channel is null");
        }
        this.selector = selector;
        this.channel = channel;
    }

    @Override
    public void run() {
        SocketChannel accept=null;
        try {
            accept = channel.accept();
            if(accept!=null){
                System.out.println("accept");
                new RWHandler(selector,accept);
            }
        } catch (IOException e) {
            if(accept!=null){
                try {
                    accept.close();
                } catch (IOException e1) {
                }
            }
            e.printStackTrace();
        }

    }
}
